﻿using System;
using System.Globalization;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using mojoPortal.Business;
using mojoPortal.Business.WebHelpers;
using mojoPortal.Web.Framework;
using mojoPortal.Web;
using Resources;
using ud_Article.Business;
using System.Collections.Generic;
using ud_Utilities;

namespace ud_Article.UI
{
    public partial class PostListCategory : UserControl
    {
        #region Properties

        private int countOfDrafts;
        private int pageNumber = 1;
        private int totalPages = 1;
        protected string EditContentImage = WebConfigSettings.EditContentImage;
        protected string EditBlogAltText = "Edit";
        protected Double TimeOffset;
        private TimeZoneInfo timeZone;
        protected DateTime CalendarDate;
        protected bool ShowGoogleMap = true;
        protected string FeedBackLabel = string.Empty;
        protected string GmapApiKey = string.Empty;
        protected bool EnableContentRating;
        private string DisqusSiteShortName = string.Empty;
        protected string disqusFlag = string.Empty;
        protected string IntenseDebateAccountId = string.Empty;
        protected bool ShowCommentCounts = true;
        protected string EditLinkText = ArticleResources.BlogEditEntryLink;
        protected string EditLinkTooltip = ArticleResources.BlogEditEntryLink;
        protected string EditLinkImageUrl = string.Empty;
        private mojoBasePage basePage;
        private Module module;
        protected ArticleConfiguration config = new ArticleConfiguration();
        private int categoryId = -1;
        private int pageId = -1;
        private int moduleId = -1;
        private string siteRoot = string.Empty;
        private string imageSiteRoot = string.Empty;
        private SiteSettings siteSettings;
        readonly DBArticleLinq repository = new DBArticleLinq();

        public PostListCategory()
        {
            IsEditable = false;
        }

        public int CategoryId
        {
            get { return categoryId; }
            set { categoryId = value; }
        }

        public int PageId
        {
            get { return pageId; }
            set { pageId = value; }
        }

        public int ModuleId
        {
            get { return moduleId; }
            set { moduleId = value; }
        }

        public string SiteRoot
        {
            get { return siteRoot; }
            set { siteRoot = value; }
        }

        public string ImageSiteRoot
        {
            get { return imageSiteRoot; }
            set { imageSiteRoot = value; }
        }

        public ArticleConfiguration Config
        {
            get { return config; }
            set { config = value; }
        }

        public bool IsEditable { get; set; }

        #endregion


        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            Load += Page_Load;
            EnableViewState = false;
            gvOthersArticle.PageIndexChanging += gvOthersArticle_PageIndexChanging;
            calBlogNav.SelectionChanged += calBlogNav_SelectionChanged;
            calBlogNav.VisibleMonthChanged += CalBlogNavVisibleMonthChanged;
            SetJQueryScript();
        }

        protected virtual void Page_Load(object sender, EventArgs e)
        {
            LoadPagingSettings();

            if (Page.IsPostBack) return;
            LoadSettings();
#if !MONO
            if (!(Page is mojoPortal.Web.UI.Pages.MyPage))
            {
                SetupRssLink();
            }
#endif

            PopulateLabels();

            PopulateControls();
        }

        private void PopulateControls()
        {
            BindBlogs();
            PopulateNavigation();
            PopulateOtherArticles();
        }

        private void PopulateOtherArticles()
        {
            if (!config.ShowOtherArticles)
            {
                pnlOthersArticle.Visible = false;
                return;
            }
            List<Business.ud_Article> result = repository.GetOthersPageCategory(categoryId,
                                                                                config.PageSize,
                                                                                pageNumber);
            gvOthersArticle.AllowPaging = config.OtherArticlesPageSizeSetting < result.Count;
            lblOtherHeader.Visible = result.Count > 0;
            gvOthersArticle.DataSource = result;
            gvOthersArticle.DataBind();
        }

        void gvOthersArticle_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvOthersArticle.PageIndex = e.NewPageIndex;
            PopulateOtherArticles();
        }

        private void BindBlogs()
        {
            rptBlogs.DataSource = repository.GetPageCategory(categoryId, config.PageSize,
                                                             pageNumber, out totalPages);
            rptBlogs.DataBind();

            string pageUrl = SiteRoot + "/Article/ViewListByCategory.aspx"
                             + "?pageid=" + pageId.ToInvariantString()
                             + "&amp;mid=" + moduleId.ToInvariantString()
                             + "&amp;cat=" + categoryId.ToInvariantString()
                             + "&amp;pagenumber={0}";

            pgr.PageURLFormat = pageUrl;
            pgr.ShowFirstLast = true;
            pgr.PageSize = config.PageSize;
            pgr.PageCount = totalPages;
            pgr.CurrentIndex = pageNumber;
            pnlBlogPager.Visible = (totalPages > 1) && config.ShowPager;
        }

        //void pgr_Command(object sender, CommandEventArgs e)
        //{
        //    pageNumber = Convert.ToInt32(e.CommandArgument);
        //    pgr.CurrentIndex = pageNumber;
        //    PopulateControls();
        //    updBlog.Update();
        //}

        protected virtual void PopulateNavigation()
        {
            Feeds.Config = config;
            Feeds.PageId = PageId;
            Feeds.ModuleId = ModuleId;
            Feeds.Visible = config.ShowFeedLinks;

            if (config.ShowCategories)
            {
                tags.CanEdit = IsEditable;
                tags.PageId = PageId;
                tags.ModuleId = ModuleId;
                tags.SiteRoot = SiteRoot;
                tags.RenderAsTagCloud = config.UseTagCloudForCategories;
            }
            else
            {
                tags.Visible = false;
                pnlCategories.Visible = false;
            }

            if (config.ShowArchives)
            {
                archive.PageId = PageId;
                archive.ModuleId = ModuleId;
                archive.SiteRoot = SiteRoot;
            }
            else
            {
                archive.Visible = false;
                pnlArchives.Visible = false;
            }

            stats.PageId = PageId;
            stats.ModuleId = ModuleId;
            stats.CountOfDrafts = countOfDrafts;
            stats.Visible = config.ShowStatistics;

        }

        private void calBlogNav_SelectionChanged(object sender, EventArgs e)
        {
            System.Web.UI.WebControls.Calendar cal = (System.Web.UI.WebControls.Calendar)sender;

            CalendarDate = cal.SelectedDate;
            //calBlogNav.VisibleDate = CalendarDate;
            //calBlogNav.SelectedDate = CalendarDate;
            //PopulateControls();

            RedirectFromCalendar();

        }

        private void CalBlogNavVisibleMonthChanged(object sender, MonthChangedEventArgs e)
        {
            CalendarDate = e.NewDate;
            //calBlogNav.VisibleDate = CalendarDate;
            //calBlogNav.SelectedDate = CalendarDate;
            //PopulateControls();

            RedirectFromCalendar();

        }

        private void RedirectFromCalendar()
        {
            string pageUrl = SiteRoot + "/Article/ViewList.aspx"
                   + "?pageid=" + pageId.ToInvariantString()
                   + "&mid=" + moduleId.ToInvariantString()
                   + "&blogdate=" + CalendarDate.Date.ToString("s");

            WebUtils.SetupRedirect(this, pageUrl);

        }

        protected virtual void PopulateLabels()
        {
            DBArticleCategory repositoryCategory = new DBArticleCategory();
            string categoryName = repositoryCategory.GetOne(categoryId).Category;
            if (categoryId > -1)
            {
                List<ud_ArticleCategory> listParent = new List<ud_ArticleCategory>();
                repositoryCategory.GetParentCategory(categoryId, ref listParent);
                if (listParent.Count > 0)
                {
                    foreach (ud_ArticleCategory articleCategory in listParent)
                    {
                        moduleTitle.LiteralExtraMarkup = "<a href = '"
                                                         + SiteRoot
                                                         + "/Article/ViewListByCategory.aspx?pageid=" +
                                                         pageId.ToInvariantString()
                                                         + "&amp;mid=" + moduleId.ToInvariantString()
                                                         + "&amp;cat=" + articleCategory.CategoryID.ToInvariantString()
                                                         + "' title='" + articleCategory.Category + "'>"
                                                         + articleCategory.Category + "</a>"
                                                         + " > "
                                                         + moduleTitle.LiteralExtraMarkup;
                    }
                    moduleTitle.LiteralExtraMarkup += categoryName;
                }
                else
                {
                    moduleTitle.LiteralExtraMarkup += categoryName;
                }
            }

            //moduleTitle.ModuleInstance = new Module(moduleId);
            if ((IsEditable) && (countOfDrafts > 0))
            {
                //BlogEditCategoriesLabel
                moduleTitle.LiteralExtraMarkup +=
                    "&nbsp;<a href='"
                    + SiteRoot
                    + "/Article/EditPost.aspx?pageid=" + pageId.ToInvariantString()
                    + "&amp;mid=" + moduleId.ToInvariantString()
                    + "&amp;catid=" + categoryId.ToInvariantString()
                    + "' class='ModuleEditLink' title='" + ArticleResources.BlogAddPostLabel + "'><img src='/Data/Icon16x16/Modify.png' alt='" + ArticleResources.BlogAddPostLabel + " |'</img></a>"
                    + "&nbsp;<a href='"
                    + SiteRoot
                    + "/Article/EditCategory.aspx?pageid=" + pageId.ToInvariantString()
                    + "&amp;mid=" + moduleId.ToInvariantString()
                    + "' class='editcategorieslink' title='" + ArticleResources.BlogEditCategoriesLabel + "'><img src='/Data/Icon16x16/Folder.png' alt='" + ArticleResources.BlogEditCategoriesLabel + " |'</img></a>"
                    + "&nbsp;<a href='"
                    + SiteRoot
                    + "/Article/Drafts.aspx?pageid=" + pageId.ToInvariantString()
                    + "&amp;mid=" + moduleId.ToInvariantString()
                    + "' class='draftlink' title='" + ArticleResources.BlogDraftsLink + "'><img src='/Data/Icon16x16/Bubble.png' alt='" + ArticleResources.BlogDraftsLink + " |'</img></a>"
                    + "&nbsp;<a href='"
                    + SiteRoot
                    + "/Article/ManagePost.aspx?pageid=" + pageId.ToInvariantString()
                    + "&amp;mid=" + moduleId.ToInvariantString()
                    + "' class='managepostlink' title='" + ArticleResources.AdminManagePostLabel + "'><img src='/Data/Icon16x16/Text.png' alt='" + ArticleResources.AdminManagePostLabel + "'</img></a>";
            }
            else if (IsEditable)
            {
                moduleTitle.LiteralExtraMarkup +=
                    "&nbsp;<a href='"
                    + SiteRoot
                    + "/Article/EditPost.aspx?pageid=" + pageId.ToInvariantString()
                    + "&amp;mid=" + moduleId.ToInvariantString()
                    + "&amp;catid=" + categoryId.ToInvariantString()
                    + "' class='ModuleEditLink' title='" + ArticleResources.BlogAddPostLabel + "'><img src='/Data/Icon16x16/Modify.png' alt='" + ArticleResources.BlogAddPostLabel + " |'</img></a>"
                    + "&nbsp;<a href='"
                    + SiteRoot
                    + "/Article/EditCategory.aspx?pageid=" + pageId.ToInvariantString()
                    + "&amp;mid=" + moduleId.ToInvariantString()
                    + "' class='editcategorieslink' title='" + ArticleResources.BlogEditCategoriesLabel + "'><img src='/Data/Icon16x16/Folder.png' alt='" + ArticleResources.BlogEditCategoriesLabel + " |'</img></a>"
                    + "&nbsp;<a href='"
                    + SiteRoot
                    + "/Article/ManagePost.aspx?pageid=" + pageId.ToInvariantString()
                    + "&amp;mid=" + moduleId.ToInvariantString()
                    + "' class='managepostlink' title='" + ArticleResources.AdminManagePostLabel + "'><img src='/Data/Icon16x16/Text.png' alt='" + ArticleResources.AdminManagePostLabel + "'</img></a>";
            }
            
            calBlogNav.UseAccessibleHeader = true;

            EditBlogAltText = ArticleResources.EditImageAltText;
            FeedBackLabel = ArticleResources.BlogFeedbackLabel;

            mojoBasePage mojoBasePage = Page as mojoBasePage;
            if (mojoBasePage != null)
            {
                if (!mojoBasePage.UseTextLinksForFeatureSettings)
                {
                    EditLinkImageUrl = ImageSiteRoot + "/Data/SiteImages/" + EditContentImage;
                }
                if (mojoBasePage.AnalyticsSection.Length == 0)
                {
                    mojoBasePage.AnalyticsSection = ConfigHelper.GetStringProperty("AnalyticsBlogSection", "blog");
                }
            }

        }

        protected string FormatPostAuthor(string authorName)
        {
            DBUtilities repositoryUtilities = new DBUtilities();
            mp_User user = repositoryUtilities.GetUser(new Guid(authorName));
            return config.ShowPostAuthor ? string.Format(CultureInfo.InvariantCulture, ArticleResources.PostAuthorFormat, config.BlogAuthor.Length > 0 ? config.BlogAuthor : user.Name) : string.Empty;
        }

        protected string FormatBlogEntry(string blogHtml, string excerpt, string url, int itemId)
        {
            if (config.UseExcerpt)
            {
                if ((excerpt.Length > 0) && (excerpt != "<p>&#160;</p>"))
                {
                    return excerpt + config.ExcerptSuffix + " <a href='" + FormatBlogUrl(url, itemId) + "' class='morelink'>" + config.MoreLinkText + "</a><div>&nbsp;</div>";
                }
                blogHtml = SecurityHelper.RemoveMarkup(blogHtml);
                if ((blogHtml.Length > config.ExcerptLength) && (config.MoreLinkText.Length > 0))
                {

                    string result = UIHelper.CreateExcerpt(blogHtml, config.ExcerptLength, config.ExcerptSuffix);
                    result += " <div class='morelink-wrapper'><div class='l'></div><div class='m'><a href='" + FormatBlogTitleUrl(url, itemId) + "' class='morelink'>" + config.MoreLinkText + "</a></div><div class='r'></div></div><div class='clear'></div>";
                    return result;
                }

            }

            return blogHtml;
        }

        protected string FormatBlogDate(DateTime startDate)
        {
            if (config.DateTimeFormat == string.Empty) return string.Empty;
            return timeZone != null ? TimeZoneInfo.ConvertTimeFromUtc(startDate, timeZone).ToString(config.DateTimeFormat) : startDate.AddHours(TimeOffset).ToString(config.DateTimeFormat);
        }

        protected string FormatBlogUrl(string itemUrl, int itemId)
        {
            if (itemUrl.Length > 0)
                return SiteRoot + itemUrl.Replace("~", string.Empty) + disqusFlag;

            return SiteRoot + "/Article/ViewPost.aspx?pageid=" + PageId.ToInvariantString()
                + "&ItemID=" + itemId.ToInvariantString()
                + "&mid=" + ModuleId.ToInvariantString()
                + disqusFlag;

        }

        protected string FormatBlogTitleUrl(string itemUrl, int itemId)
        {
            if (itemUrl.Length > 0)
                return SiteRoot + itemUrl.Replace("~", string.Empty);

            return SiteRoot + "/Article/ViewPost.aspx?pageid=" + PageId.ToInvariantString()
                + "&ItemID=" + itemId.ToInvariantString()
                + "&mid=" + ModuleId.ToInvariantString();

        }

        private string GetRssUrl()
        {
            if (config.FeedburnerFeedUrl.Length > 0) return config.FeedburnerFeedUrl;

            return SiteRoot + "/blog" + ModuleId.ToInvariantString() + "rss.aspx";

        }

        protected string FormatBlogTitle(string title, int maxChars)
        {
            if (title.Length > maxChars)
            {
                title = title.Remove(maxChars);
                title += "...";
            }
            return title;
        }

        protected string FormatTooltip(string title, string content)
        {
            string result;
            if (config.UseTooltipSettings)
            {
                if (content.Length > config.TooltipMaxCharSettings)
                {
                    content = UIHelper.CreateExcerpt(content, config.TooltipMaxCharSettings, "...");
                }
                result = "<div class='tooltip'><div class='title-l'></div><div class='title-m'>" + title + "</div><div class='title-r'></div><div class='body'>" + content + "</div></div>";
            }
            else
            {
                result = title;
            }
            return result;
        }

        protected string BuildEditUrl(int itemID)
        {
            return SiteRoot + "/Article/EditPost.aspx?pageid=" + pageId + "&ItemID=" +
                       itemID + "&mid=" + moduleId;
        }

        private void SetJQueryScript()
        {
            StringBuilder sb = ArticleUtils.SetJQueryScript(config, moduleId);
            if (!Page.ClientScript.IsStartupScriptRegistered(typeof(Page), "postlist" + moduleId))
            {
                Page.ClientScript.RegisterStartupScript(typeof(Page), "postlist" + moduleId, sb.ToString());
            }
            if (Page.ClientScript.IsStartupScriptRegistered(typeof(Page), "jquerytool")) return;
            string script = "<script src='" + imageSiteRoot + "/ClientScript/jqmojo/jquery.tools.min.js'></script>";
            Page.ClientScript.RegisterStartupScript(typeof(Page), "jquerytool", script);
        }

        protected virtual void LoadSettings()
        {
            LoadPagingSettings();
            siteSettings = CacheHelper.GetCurrentSiteSettings();
            TimeOffset = SiteUtils.GetUserTimeOffset();
            timeZone = SiteUtils.GetUserTimeZone();
            GmapApiKey = SiteUtils.GetGmapApiKey();
            pageNumber = WebUtils.ParseInt32FromQueryString("pagenumber", pageNumber);

            if (Page is mojoBasePage)
            {
                basePage = Page as mojoBasePage;
                module = basePage.GetModule(moduleId);
            }

            CalendarDate = WebUtils.ParseDateFromQueryString("blogdate", DateTime.UtcNow).Date;

            if (CalendarDate > DateTime.UtcNow.Date)
            {
                CalendarDate = DateTime.UtcNow.Date;
            }

            if ((config.UseExcerpt) && (!config.GoogleMapIncludeWithExcerpt)) { ShowGoogleMap = false; }

            EnableContentRating = config.EnableContentRating;
            if (config.UseExcerpt) { EnableContentRating = false; }

            DisqusSiteShortName = config.DisqusSiteShortName.Length > 0 ? config.DisqusSiteShortName : siteSettings.DisqusSiteShortName;

            IntenseDebateAccountId = config.IntenseDebateAccountId.Length > 0 ? config.IntenseDebateAccountId : siteSettings.IntenseDebateAccountId;

            if (config.AllowComments)
            {
                if ((DisqusSiteShortName.Length > 0) && (config.CommentSystem == "disqus"))
                {
                    disqusFlag = "#disqus_thread";
                    disqus.SiteShortName = DisqusSiteShortName;
                    disqus.RenderCommentCountScript = true;
                    stats.ShowCommentCount = false;

                }

                if ((IntenseDebateAccountId.Length > 0) && (config.CommentSystem == "intensedebate"))
                {
                    ShowCommentCounts = false;
                    stats.ShowCommentCount = false;
                }
            }


            if (!config.NavigationOnRight)
            {
                divNav.CssClass = "blognavleft";
                divblog.CssClass = "blogcenter-leftnav";

            }
            if (config.ShowCalendar)
            {
                calBlogNav.Visible = true;
                try
                {
                    calBlogNav.FirstDayOfWeek = (FirstDayOfWeek)CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek;
                }
                catch (ArgumentNullException) { }
                catch (ArgumentOutOfRangeException) { }
                catch (InvalidOperationException) { }
                catch (InvalidCastException) { }

                if (!Page.IsPostBack)
                {
                    calBlogNav.SelectedDate = CalendarDate;
                    calBlogNav.VisibleDate = CalendarDate;

                }
            }
            else
            {
                calBlogNav.Visible = false;
            }

            if (config.Copyright.Length > 0)
            {
                lblCopyright.Text = config.Copyright;
            }

            pnlStatistics.Visible = config.ShowStatistics;

            divNav.Visible = false;

            if (config.ShowCalendar
                || config.ShowArchives
                || config.ShowAddFeedLinks
                || config.ShowCategories
                || config.ShowFeedLinks
                || config.ShowStatistics)
            {
                divNav.Visible = true;
            }

            if (!divNav.Visible)
            {
                divblog.CssClass = "blogcenter-nonav";
            }
            if (IsEditable)
            {
                countOfDrafts = Article.CountOfDrafts(ModuleId);
            }


        }

        private void LoadPagingSettings()
        {
            gvOthersArticle.PageSize = config.OtherArticlesPageSizeSetting;
            gvOthersArticle.AllowPaging = config.OtherArticlesUsePaging;
        }


        protected virtual void SetupRssLink()
        {
            if (WebConfigSettings.DisableBlogRssMetaLink) { return; }

            if (module == null) return;
            if (Page.Master != null)
            {
                Control head = Page.Master.FindControl("Head1");
                if (head != null)
                {
                    Literal rssLink = new Literal
                                          {
                                              Text = @"<link rel=""alternate"" type=""application/rss+xml"" title="""
                                                     + module.ModuleTitle + @""" href="""
                                                     + GetRssUrl() + @""" />"
                                          };

                    head.Controls.Add(rssLink);
                }
            }
        }
    }
}